<template>
  <div class="GiveAlarm">
    <div class="GiveAlarm-content">
      <img class="alarm-img" :src="alarmImg" alt="">
      <img class="auto-img" :src="audioImg" alt="" @click="audioChange">
      <MyAudio v-if="formData.status" ref="audioRef" @endPlay="endPlay" :timeNum="timeNum"></MyAudio>
    </div>
  </div>
</template>

<script setup lang="ts">
import { createMqttClient } from '@/utils/mqtt';
import onAlarmImg from '@/assets/gif/alarm.gif'
import offAlarmImg from '@/assets/index/off-alarm.png'
import onAudioImg from '@/assets/index/on-audio.png'
import offAudioImg from '@/assets/index/off-audio.png'

const emit = defineEmits(['updateGiveAlarm']);

const mqttClient = createMqttClient({ url: '/barco/transit/safety/prompt' });
const audioRef = ref();
const alarmImg = ref(offAlarmImg);
const audioImg = ref(offAudioImg);
const timeNum = 800

const mqttOptions = reactive({
  url: '/barco/transit/alarm/data' // /barco/transit/alarm/data
})
const formData = reactive<any>({
  status: false
});

const initMqtt = async () => {
  // 在组件挂载时订阅主题
  // /barco/transit/vehicle/position
  mqttClient.subscribe(mqttOptions.url);
  mqttClient.on('message', (topic: string, message: Buffer) => {
    let decoded = new TextDecoder('utf-8').decode(message); //转义
    if (mqttOptions.url !== topic) return
    console.log('告警', topic, JSON.parse(decoded));
    // 实时获取车的当前信息，车是所有车辆，但是一次只返回一辆
    let params = JSON.parse(decoded);
    // 处理消息逻辑...
    updateData(params)
  });
}

function updateData(params: any) {
  alarmImg.value = onAlarmImg
  emit('updateGiveAlarm', params)
  // 开就播放
  if (formData.status) {
    return audioRef.value.handleCanPlay()
  }
  setTimeout(() => {
    endPlay()
  }, timeNum)
}

function audioChange() {
  formData.status = !formData.status
}

// 播放完成
function endPlay() {
  alarmImg.value = offAlarmImg
}

watch(() => formData.status, () => {
  if (formData.status) {
    return audioImg.value = onAudioImg
  }
  return audioImg.value = offAudioImg
}, { immediate: true })

onMounted(async () => {
  initMqtt()

})

// 在组件卸载时断开连接
onUnmounted(() => {
  mqttClient.end(true);
});



</script>

<style lang="scss" scoped>
.GiveAlarm {
  position: fixed;
  right: 90px;
  top: 108px;
  z-index: 100;


  .GiveAlarm-content {
    display: flex;
    // flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 60px;

    .auto-img {
      width: 50px;
      cursor: pointer;
    }

    .alarm-img {
      width: 50px;
    }
  }
}
</style>
